package org.cloudie.docs.editor.server.auth;

import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.logging.Level;
import java.util.logging.Logger;

public class AuthenticationKey {

  protected AuthenticationKey() { }
  
  private static PrivateKey authSubKey;
  private static final Logger log = Logger.getLogger(AuthenticationKey.class.getName());
  
  public static PrivateKey getAuthSubKey() {
	if (authSubKey == null) {
	  try {
		CertificateStore certStore = new CertificateStore();
		Certificate cert = certStore.getCertificate("gdata");
		
		if (cert == null) {
		  try {
			/*prod*/Certificate.putCertificate("gdata", "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBALWUfR1by8VjePV/vaYUNJika4/KDbmYlfU430HRCdjk2ViTRyZjZPmb/6I5rlA19pfvNEqQvU8Ub0Af5TazOLRYrnzAPL5JzosaKC6SSXe+dsRDf3G+Zlsuu/6kzaXUIxSbyqqyV3HRyc1sFkOg0zmKlfemZ1KZhwzjqglnWe6fAgMBAAECgYBqVmdfBh8znal8vC5oUHTs331OW9nl0wIe9gtpE+5cYskWIkoMpTDBLSZr7rOyraeYGrHY6SK0aRctyoAFpLeTiLdxsYQWNP3MkA94bi1n5/pcmex2wS8k4z5pksOb7iwYTxKQQ0q33SuJTtwpcngcLorfV3J8rin6rsal9vvP4QJBAOwytKi3o21OmpoGZS2KZTqLkQ2Ww8zM6y4zU4h/zY5KLKUMqfe3WzuqtJPUnvFj0VEVqt+06WggnXO0KSC5wTUCQQDEzZFxlObTuMkN4rXn3nz2JljUCZlIMRpJxtQjLgYLeFUlcNIGkKVUAtNn6+PSFTWKYFLzWRVijf82v5pV0l8DAkBX6OdkhDTHUiIogYjW0lOq3pc2P47QgtRldaT5gNe4xdKn+3anRA8ovfhHrTMbFNOrIi1e5a6Zmsn/bmaAT6KhAkB5YBsahO4Tl/yPzsnHtkU1fpL8OutJRddjtvewtrrNqipBTCKMH/uHI7MEfcxlDeWWcS/Xm5J/1PmY53SlB3jHAkEAoWmpHxq+vXL1NWsTOD0XTvl/H5EEHEdD5vNRCK2HSjPBlxfKiQkxa7vrzGaPmCj895qT9CZDX1x8y3IAmQgc+w=="); //for local testing
			cert = certStore.getCertificate("gdata");
		  } catch (Exception x) { }
		}
	    byte[] encodedKey = cert.getKey().getBytes();
	    byte[] decodedBuffer = com.google.appengine.repackaged.com.google.common.util.Base64.decode(encodedKey);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(decodedBuffer);
        authSubKey = keyFactory.generatePrivate(privateKeySpec);
	  } catch (Exception x) {
        log.log(Level.SEVERE, "AuthSub key generation failed: "  + x.getMessage(), x);
	  }
	}
	return authSubKey;
  }
  
}
